package com.example.cofeed.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.cofeed.R;
import com.example.cofeed.adapter.PayAdapter;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.Constants;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.entity.PayWay;
import com.example.cofeed.even.WeixinPayEven;
import com.example.cofeed.pay.AuthResult;
import com.example.cofeed.pay.PayResult;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by mqwang on 2017/9/26.
 */

public class PayActivity extends BaseActivity {
    @BindView(R.id.tv_pay)
    TextView moneyTv;
    @BindView(R.id.rec_lv)
    RecyclerView recLv;
    private String orderId;
    private String money;
    private PayAdapter payAdapter;
    private String payCode;
    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        setMainTitle("选择支付方式");

        orderId = getIntent().getStringExtra(IntentKeyConstant.ORDER_ID);
        money = getIntent().getStringExtra(IntentKeyConstant.MONEY);
        type = getIntent().getIntExtra(IntentKeyConstant.TYPE, 0);
        moneyTv.setText(money);

        recLv.setLayoutManager(new LinearLayoutManager(this));
        payAdapter = new PayAdapter();
        recLv.setAdapter(payAdapter);

        payAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PayWay payWay = (PayWay) adapter.getData().get(position);
                payAdapter.setSelect(payWay);
                payCode = payWay.code;

            }
        });

        getData();
    }

    private void getData() {

        ApiService.payment(this, new DialogCallback<LzyResponse<PayWay>>(this) {
            @Override
            public void onSuccess(Response<LzyResponse<PayWay>> response) {
                payAdapter.setNewData(response.body().data.pays);

            }
        });

    }

    @OnClick(R.id.confirm_tv)
    public void onViewClicked() {
        if (ObjectUtils.isEmpty(payCode)) {
            showToast("请选择支付方式");
            return;
        }

        ApiService.paymentGetPaymentInfo(this, orderId, payCode, new DialogCallback<LzyResponse<Map<String, String>>>(this) {
            @Override
            public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
                if (!ObjectUtils.isEmpty(payCode)) {
                    switch (payCode) {
                        case "alipay":
                            final String orderInfo = response.body().data.get("query_str");
                            Runnable payRunnable = new Runnable() {

                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(PayActivity.this);
                                    Map<String, String> result = alipay.payV2(orderInfo, true);

                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };

                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                            break;
                        case "wechat":
                            IWXAPI api = WXAPIFactory.createWXAPI(PayActivity.this, Constants.WEIXIN_APP_ID);
                            PayReq req = new PayReq();
                            //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                            req.appId = (String) response.body().data.get("appid");
                            req.partnerId = (String) response.body().data.get("partnerid");
                            req.prepayId = (String) response.body().data.get("prepayid");
                            req.nonceStr = (String) response.body().data.get("noncestr");
                            req.timeStamp = (String) response.body().data.get("timestamp");
                            req.packageValue = (String) response.body().data.get("package");
                            req.sign = (String) response.body().data.get("sign");
                            api.sendReq(req);
                            break;
                    }
                }

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void weixinPay(WeixinPayEven weixinPayEven) {
        setResult(RESULT_OK);
        switch (weixinPayEven.code) {
            case 0:
                showToast("支付成功");
                finish();
                if (type > 0) {
                    ActivityUtils.startActivity(MySubscriptionActivity.class);
                }
                break;
            case -1:
                showToast("未知错误");
                break;
            case -2:
                showToast("用户取消");
                break;
            default:
//					builder = new AlertDialog.Builder(this);
//					builder.setMessage(String.valueOf(resp.errCode));
//					builder.show();
                break;
        }

    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支付成功");
                        setResult(RESULT_OK);
                        finish();
                        if (type > 0) {
                            ActivityUtils.startActivity(MySubscriptionActivity.class);
                        }

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        setResult(RESULT_OK);
                        showToast("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showToast("授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()));

                    } else {
                        // 其他状态值则为授权失败
                        showToast("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
